package model

import (
	"blog2021/tools/logger"
	"math"
	"math/rand"
	"sort"
	"strings"
	"time"

	"github.com/jinzhu/gorm"
)

type Tag struct {
	gorm.Model
	Name string `gorm:"column:name"`
}

type HtmlTag struct {
	Id       int
	Name     string
	Red      int
	Green    int
	Blue     int
	FontSize int
	Count    int
}

var htmlTags []HtmlTag

func AllTags() []Tag {
	var tags []Tag
	if err := db.Find(&tags).Error; err != nil {
		logger.Error(err)
	}
	return tags
}

func InitHtmlTags() {
	var tagCount = make(map[string]int)
	var tagTotal int
	tags := AllTags()
	var posts []Post
	if err := db.Select("tags").Find(&posts).Error; err == nil {
		for _, post := range posts {
			ls := strings.Split(post.Tags, ";")
			for _, v := range ls {
				if len(v) > 0 {
					tagCount[v] += 1
				}
			}
		}
		tagTotal = 0
		for _, v := range tagCount {
			tagTotal += v
		}
	}

	htmlTags = []HtmlTag{}
	for i, tag := range tags {
		rand.Seed(time.Now().UnixNano() + int64(i))
		fontSize := float64(12) + float64(tagCount[tag.Name])/float64(tagTotal)*70
		fontSize = math.Min(30, fontSize)
		htmlTags = append(htmlTags, HtmlTag{
			Id:       rand.Intn(100),
			Name:     tag.Name,
			Red:      rand.Intn(256),
			Green:    rand.Intn(256),
			Blue:     rand.Intn(256),
			FontSize: int(fontSize),
			Count:    tagCount[tag.Name],
		})
	}

	sort.Slice(htmlTags, func(i, j int) bool {
		return htmlTags[i].Id < htmlTags[j].Id
	})
}

func HtmlTags() []HtmlTag {
	return htmlTags
}
